import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class WriteDataToCSV {
    public static void writeDataToCSV(List<String> headers, List<List<String>> data, String filePath) {
        try (FileWriter writer = new FileWriter(filePath)) {
            // 写入表头
            writeLine(headers, writer);
            // 写入数据行
            for (List<String> rowData : data) {
                writeLine(rowData, writer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void writeLine(List<String> rowData, FileWriter writer) throws IOException {
        StringBuilder line = new StringBuilder();
        for (int i = 0; i < rowData.size(); i++) {
            line.append(escapeSpecialCharacters(rowData.get(i)));
            if (i != rowData.size() - 1) {
                line.append(",");
            }
        }
        line.append("\n");
        writer.append(line.toString());
    }
    private static String escapeSpecialCharacters(String cell) {
        if (cell.contains(",") || cell.contains("\"") || cell.contains("\n")) {
            cell = "\"" + cell.replace("\"", "\"\"") + "\"";
        }
        return cell;
    }
}

